package com.sk.weichat.ui.me;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.Report;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.message.TabFansEditActivity;
import com.sk.weichat.ui.message.single.SetLabelActivity;
import com.sk.weichat.ui.message.single.SetLabelActivity2;
import com.sk.weichat.ui.message.single.SetRemarkActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.ReportDialog;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.sk.weichat.xmpp.listener.NewFriendListener;
import com.suke.widget.SwitchButton;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.Call;

/**
 * 他人的个人信息—更多
 * create by swy 2019-06-25
 */
public class PersonalCenterMoreActivity extends BaseActivity implements NewFriendListener, View.OnClickListener {

    private static final int REQUEST_CODE_SET_REMARK = 201;
    private SwitchButton mSwitchToBlack;
    private String mUserId;
    private Friend mFriend;
    private String mAddblackid;
    private String mLoginUserId;
    private String mRemoveblack;
    // private boolean isShowDialog;

    GestureDetector gestureDetector;

    AtomicBoolean isClickAble = new AtomicBoolean(true);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_more);
        initActionBar();
        initView();
        ListenerManager.getInstance().addNewFriendListener(this);
        //拉黑按钮
        gestureDetector = new GestureDetector(mContext, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }

            @Override
            public void onShowPress(MotionEvent e) {
                Log.e("lzs", "onShowPress ");
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (!mSwitchToBlack.isChecked()) {
                    if (mBlacklistDialog == null) {
                        setupBlacklistDialog(mFriend);
                    }
                    if (!mBlacklistDialog.isShowing()) {
                        mBlacklistDialog.show();
                    }
                } else {
                    if (isClickAble.get()) {
                        isClickAble.set(false);
                        removeBlacklist(mFriend);
                    }
                }
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                return false;
            }
        });
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.more);
        findViewById(R.id.iv_title_left).setOnClickListener(this);
    }

    private void initView() {
        mUserId = getIntent().getStringExtra(AppConstant.EXTRA_USER_ID);
        mLoginUserId = coreManager.getSelf().getUserId();
        mFriend = FriendDao.getInstance().getFriend(mLoginUserId, mUserId);

        if (mFriend.getStatus() == Friend.STATUS_FRIEND) {
            findViewById(R.id.layout_more_label).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.layout_more_label).setVisibility(View.GONE);
        }

        if (mFriend.getStatus() == Friend.STATUS_FRIEND || mFriend.getStatus() == Friend.STATUS_ATTENTION) {//好友和关注时显示取消关注按钮
            findViewById(R.id.layout_more_attention).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.layout_more_attention).setVisibility(View.GONE);
        }

        if (mFriend.getStatus() == Friend.STATUS_FRIEND || mFriend.getStatus() == Friend.STATUS_BE_ATTENTION) {//好友和被关注时显示移除粉丝按钮
            findViewById(R.id.layout_more_fans).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.layout_more_fans).setVisibility(View.GONE);
        }

        findViewById(R.id.layout_more_remark).setOnClickListener(this);
        findViewById(R.id.layout_more_label).setOnClickListener(this);
        findViewById(R.id.layout_more_report).setOnClickListener(this);
        findViewById(R.id.layout_more_attention).setOnClickListener(this);
        findViewById(R.id.layout_more_fans).setOnClickListener(this);

        //拉黑
        mSwitchToBlack = (SwitchButton) findViewById(R.id.switch_to_black);
        mSwitchToBlack.setChecked(mFriend.getStatus() == Friend.STATUS_BLACKLIST);

        mSwitchToBlack.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });

    }

    @Override
    public void onNewFriendSendStateChange(String toUserId, NewFriendMessage message, int messageState) {
        if (messageState == ChatMessageListener.MESSAGE_SEND_SUCCESS) {
            msgSendSuccess(message, message.getPacketId());
        } else if (messageState == ChatMessageListener.MESSAGE_SEND_FAILED) {
            msgSendFailed(message.getPacketId());
        }

    }

    private void msgSendSuccess(NewFriendMessage message, String packetId) {

        if (mAddblackid != null && mAddblackid.equals(packetId)) {//拉黑成功
            Toast.makeText(getApplicationContext(), getString(R.string.add_blacklist_succ), Toast.LENGTH_SHORT).show();
            // 更新当前持有的Friend对象，
            mFriend.setStatus(Friend.STATUS_BLACKLIST);
            FriendDao.getInstance().updateFriendStatus(message.getOwnerId(), message.getUserId(), mFriend.getStatus());
            FriendHelper.addBlacklistExtraOperation(message.getOwnerId(), message.getUserId());

            ChatMessage addBlackChatMessage = new ChatMessage();
            addBlackChatMessage.setContent("你拉黑了" + mFriend.getNickName());
            addBlackChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
            FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, addBlackChatMessage);

            NewFriendDao.getInstance().createOrUpdateNewFriend(message);
            NewFriendDao.getInstance().changeNewFriendState(mUserId, Friend.STATUS_18);
            ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

            CardcastUiUpdateUtil.broadcastUpdateUi(mContext);

        } else if (mRemoveblack != null && mRemoveblack.equals(packetId)) {//移出黑名单
            Toast.makeText(getApplicationContext(), InternationalizationHelper.getString("REMOVE_BLACKLIST"), Toast.LENGTH_SHORT).show();

            // 更新当前持有的Friend对象，
            if (mFriend != null) {
                mFriend.setStatus(Friend.STATUS_UNKNOW);
            }
            //NewFriendDao.getInstance().ascensionNewFriend(message, Friend.STATUS_UNKNOW);
            // FriendHelper.beAddFriendExtraOperation(message.getOwnerId(), message.getUserId());

            ChatMessage removeChatMessage = new ChatMessage();
            removeChatMessage.setContent("你把" + mFriend.getNickName() + "移出黑名单");
            removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
            FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);
            NewFriendDao.getInstance().createOrUpdateNewFriend(message);
            NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_29);
            ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

            CardcastUiUpdateUtil.broadcastUpdateUi(mContext);

        }
    }

    public void msgSendFailed(String packet) {
        DialogHelper.dismissProgressDialog();
        if (packet.equals(mAddblackid)) {
            Toast.makeText(this, R.string.tip_put_black_failed, Toast.LENGTH_SHORT).show();
        } else if (packet.equals(mRemoveblack)) {
            Toast.makeText(this, R.string.tip_remove_black_failed, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onNewFriend(NewFriendMessage message) {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.layout_more_remark://备注和描述
                SetRemarkActivity.startForResult(PersonalCenterMoreActivity.this, mUserId, REQUEST_CODE_SET_REMARK);
                break;

            case R.id.layout_more_label://标签
                Intent intentLabel = new Intent(this, SetLabelActivity2.class);
                intentLabel.putExtra(AppConstant.EXTRA_USER_ID, mUserId);
                startActivity(intentLabel);
                break;

            case R.id.layout_more_report://举报
                ReportDialog mReportDialog = new ReportDialog(PersonalCenterMoreActivity.this, false, new ReportDialog.OnReportListItemClickListener() {
                    @Override
                    public void onReportItemClick(Report report) {
                        report(mFriend, report);
                    }
                });
                mReportDialog.show();
                break;

            case R.id.layout_more_attention://取消关注
                cancelAttention(mFriend);
                break;

            case R.id.layout_more_fans://移除粉丝
                removeFans(mFriend.getUserId());
                break;

        }
    }

    /**
     * 服务器移除粉丝操作
     */
    private void removeFans(String toUserIds) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId",toUserIds);

        HttpUtils.post().url(coreManager.getConfig().FRIENDS_FANS_DELETE)
                .params(params)
                .build()
                .execute(new ListCallback<User>(User.class) {
                    @Override
                    public void onResponse(ArrayResult<User> result) {

                        if (result.getResultCode() == 1) {
                            findViewById(R.id.layout_more_fans).setVisibility(View.GONE);
                            ToastUtil.showToast(PersonalCenterMoreActivity.this, result.getResultMsg());
                            //好友移粉需要在关系通知提醒
                            if (mFriend.getStatus() == Friend.STATUS_FRIEND) {
                                ChatMessage removeChatMessage = new ChatMessage();
                                removeChatMessage.setContent("你移除" + mFriend.getNickName() + "粉丝，解除好友关系");
                                removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);

                                NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                        coreManager.getSelf(), XmppMessage.TYPE_CANCEL_FANS, null, mFriend);

                                NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                                NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_31);
                                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);
                                FriendDao.getInstance().updateFriendStatus(mLoginUserId,message.getUserId(),Friend.STATUS_ATTENTION);

                                CardcastUiUpdateUtil.broadcastUpdateUi(PersonalCenterMoreActivity.this);
                            }
                        } else {
                            ToastUtil.showToast(PersonalCenterMoreActivity.this, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showErrorNet(PersonalCenterMoreActivity.this);
                    }
                });
    }

    private void cancelAttention(Friend friend) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", friend.getUserId());
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().CANEL_ATTENTION)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            findViewById(R.id.layout_more_attention).setVisibility(View.GONE);
                            ToastUtil.showToast(PersonalCenterMoreActivity.this, result.getResultMsg());

                            //好友取消关注需要在关系通知提醒
                            if (mFriend.getStatus() == Friend.STATUS_FRIEND) {
                                ChatMessage removeChatMessage = new ChatMessage();
                                removeChatMessage.setContent("你取关了" + mFriend.getNickName() + "，解除好友关系");
                                removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);

                                NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                        coreManager.getSelf(), XmppMessage.TYPE_CANCEL_ATTENTION, null, friend);

                                NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                                NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_27);
                                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);
                                FriendDao.getInstance().updateFriendStatus(mLoginUserId,message.getUserId(),Friend.STATUS_BE_ATTENTION);

                                CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
                            }
                        } else {
                            ToastUtil.showToast(PersonalCenterMoreActivity.this, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }


    /**
     * 举报
     *
     * @param friend
     * @param report
     */
    private void report(Friend friend, Report report) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", friend.getUserId());
        params.put("reason", String.valueOf(report.getReportId()));
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().USER_REPORT)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            ToastUtil.showToast(PersonalCenterMoreActivity.this, R.string.report_success);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    //拉黑弹窗
    SelectionFrame mBlacklistDialog;

    /**
     * 加入黑名单弹框
     */
    private void setupBlacklistDialog(final Friend friend) {

        mBlacklistDialog = new SelectionFrame(this);
        mBlacklistDialog.setSomething(getString(R.string.dialog_title), getString(R.string.sure_add_friend_blacklist), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {
                mSwitchToBlack.setChecked(false);
            }

            @Override
            public void confirmClick() {
                mSwitchToBlack.setChecked(true);
                //isShowDialog=false;
                addBlacklist(friend);
            }
        });
    }

    /**
     * 加入黑名单
     *
     * @param friend
     */
    private void addBlacklist(final Friend friend) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", friend.getUserId());
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_BLACKLIST_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            findViewById(R.id.layout_more_attention).setVisibility(View.GONE);
                            NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                    coreManager.getSelf(), XmppMessage.TYPE_BLACK, null, friend);
                            coreManager.sendNewFriendMessage(friend.getUserId(), message);// 加入黑名单
                            mAddblackid = message.getPacketId();
                            FriendDao.getInstance().updateFriendStatus(mLoginUserId, friend.getUserId(), Friend.STATUS_BLACKLIST);
                        } else if (!TextUtils.isEmpty(result.getResultMsg())) {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        } else {
                            ToastUtil.showToast(mContext, R.string.tip_server_error);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(mContext, getString(R.string.add_blacklist_fail), Toast.LENGTH_SHORT).show();
                    }
                });
    }


    /**
     * 移出黑名单
     *
     * @param friend
     */
    private void removeBlacklist(final Friend friend) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", mUserId);
        DialogHelper.showDefaulteMessageProgressDialog(this);
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_BLACKLIST_DELETE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                    coreManager.getSelf(), XmppMessage.TYPE_REFUSED, null, friend);
                            coreManager.sendNewFriendMessage(friend.getUserId(), message);// 移除黑名单
                            mRemoveblack = message.getPacketId();
                            // TODO: 2019/7/23 被关注 
                            FriendDao.getInstance().updateFriendStatus(mLoginUserId, friend.getUserId(), Friend.STATUS_UNKNOW);
                            mSwitchToBlack.setChecked(false);
                        } else if (!TextUtils.isEmpty(result.getResultMsg())) {
                            Log.e("lzs", "result.getResultMsg():" + result.getResultMsg());
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        } else {
                            ToastUtil.showToast(mContext, R.string.tip_server_error);
                        }
                        mSwitchToBlack.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isClickAble.set(true);
                            }
                        },1000);

                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        mSwitchToBlack.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isClickAble.set(true);
                            }
                        },1000);
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(mContext, R.string.tip_remove_black_failed, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    protected void onDestroy() {
        super.onDestroy();
        ListenerManager.getInstance().removeNewFriendListener(this);
    }


}
